package com.requestGwsLongGangQu;

import java.io.File;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.yishun.springboot.pojo.GwsLonggangquVehicleDetailed;
import com.yishun.springboot.pojo.PinyiVehicleDetailed;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Vehicle {

	// private String api_key = "f0328808bad1481cad0e9207c6f67947";
	// 环境：642ef1804ff04ffcb2f87de5ee5e55b4
	private static String api_key = "a684b22a61f04f5499039ee9eebdd3a1";
	private static String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
	private static String api_version = "1.0";
	private static String engCode = "XM20230098-1";
	private static String projectCode = "XM20230098";

	private static final String GWS_URL = "http://218.17.147.31:66/openapi/";

	/**
	 * 上传车道闸基础信息
	 */
	// @Test
	public String uploadVehicleBasic(String api_version, String no, String api_key, String project_code,
			String eng_code, PinyiVehicleDetailed pinyiVehicleDetailed) {
		String url = GWS_URL + "vehicle/addBasicInfo";
		JSONObject param = new JSONObject();
		JSONObject body = new JSONObject();

		param.put("api_key", api_key);
		param.put("project_code", project_code);
		param.put("eng_code", eng_code);
		param.put("api_version", api_version);
		param.put("timestamp", timestamp);

		body.put("device_no", no);
		body.put("name", pinyiVehicleDetailed.getName());
		body.put("region_no", pinyiVehicleDetailed.getRegionNo());
		body.put("region_type", pinyiVehicleDetailed.getRegionType());
		body.put("region_name", pinyiVehicleDetailed.getRegionName());
		body.put("install_company", pinyiVehicleDetailed.getInstallCompany());
		param.put("body", body);// body

		String jsonBody = JSONObject.toJSONString(body);// body的json字符串

		String signature = getSignature(api_key, api_version, eng_code, project_code, timestamp, jsonBody);
		param.put("signature", signature);

		log.info(param.toJSONString());
		// 发送请求
		String s = param.toJSONString();
		String info = HttpUtil.post(url, s);
		log.info(info);
		return info;
	}

	public String httpPostVehicleDetailed(GwsLonggangquVehicleDetailed gwsLonggangquVehicleDetailed) {
		String url = GWS_URL + "vehicle/heartbeat";

		JSONObject param = new JSONObject();
		JSONObject body = new JSONObject();

		param.put("api_key", gwsLonggangquVehicleDetailed.getApi_key());
		param.put("project_code", gwsLonggangquVehicleDetailed.getProject_code());
		param.put("eng_code", gwsLonggangquVehicleDetailed.getEng_code());
		param.put("api_version", gwsLonggangquVehicleDetailed.getApi_version());
		param.put("timestamp", timestamp);
		body.put("device_no", gwsLonggangquVehicleDetailed.getDevice_no());
		body.put("beat_time", timestamp);
		param.put("body", body);// body
		String jsonBody = JSONObject.toJSONString(body);// body的json字符串

		String signature = getSignature(gwsLonggangquVehicleDetailed.getApi_key(),
				gwsLonggangquVehicleDetailed.getApi_version(), gwsLonggangquVehicleDetailed.getEng_code(),
				gwsLonggangquVehicleDetailed.getProject_code(), timestamp, jsonBody);
		param.put("signature", signature);

		log.info(param.toJSONString());
		// 发送请求
		String s = param.toJSONString();
		String info = HttpUtil.post(url, s);
		log.info(info);

		return info;
	}

	public String uploadImage(String api_key, String photoUrl) {

		photoUrl = photoUrl.replace("\\", "\\\\");

		log.info("上传图片数据给工务署平台..");
		HashMap<String, Object> paramMap = new HashMap<>();
		String url = "http://218.17.147.31:66/uploadfile-openpai/uploadImage";
		// 文件
		File file = new File(photoUrl);
//		log.info("file:"+file.getAbsolutePath());
		paramMap.put("file", file);
		paramMap.put("api_key", api_key);
		String result = HttpUtil.post(url, paramMap);
		log.info("上传图片结果：" + result);// 返回文件的id
		// resultData":"ffbe6ac3b17f5a457cbd1a7abfe2ff1e"
		// 解析失败则请求失败或者没有其他异常，抛空
		String gwsPhotoUrl = "";
		try {
			gwsPhotoUrl = JSONObject.parseObject(result).getString("resultData");
		} catch (Exception e) {
			return null;
		}
		return gwsPhotoUrl;
	}

	public String uploadData(JSONObject param, JSONObject body) {
		log.info("上传车辆进出场数据给工务署平台..");
		String url = GWS_URL + "/vehicle/uploadData";

		List<JSONObject> bodyList = new ArrayList<>();// 可以传入多个body
		bodyList.add(body);
		param.put("body", bodyList);// body

		String jsonBody = JSONObject.toJSONString(bodyList);// body的json字符串

		String timestamp = param.getString("timestamp");// 封装原方法参数
		String api_key = param.getString("api_key");
		String projectCode = param.getString("project_code");
		String engCode = param.getString("eng_code");
		String api_version = param.getString("api_version");

		String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, jsonBody);
		param.put("signature", signature);

		String info = HttpUtil.post(url, param.toJSONString());

		return info;

		// return parseResult(info, param, url);
	}



	/**
	 * 获取签名
	 *
	 * @param: [apiKey, apiVersion, engCode, projectCode, timestamp, body]
	 * @return: java.lang.String
	 */
	public static String getSignature(String apiKey, String apiVersion, String engCode, String projectCode,
			String timestamp, String body) {
		String str4MD5 = String.format("api_key%sapi_version%sbody%seng_code=%sproject_code=%stimestamp%s", apiKey,
				apiVersion, body.isEmpty() ? "{}" : body, engCode, projectCode, timestamp);
		return getMD5Code(str4MD5);
	}

	public static String getMD5Code(String strObj) {
		String resultString = null;
		try {
			resultString = new String(strObj);
			MessageDigest md = MessageDigest.getInstance("MD5");
			Charset charset = Charset.forName("UTF-8");
			resultString = byteToString(md.digest(strObj.getBytes(charset)));
		} catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}
		return resultString;
	}

	// 转换字节数组为16进制字串
	private static String byteToString(byte[] bByte) {
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < bByte.length; i++) {
			sBuffer.append(byteToArrayString(bByte[i]));
		}
		return sBuffer.toString();
	}

	private static String byteToArrayString(byte bByte) {
		int iRet = bByte;
		if (iRet < 0) {
			iRet += 256;
		}
		int iD1 = iRet / 16;
		int iD2 = iRet % 16;
		return strDigits[iD1] + strDigits[iD2];
	}

	// 全局数组
	private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D",
			"E", "F" };

	/**
	 * signature生成
	 */
	// @Test
	public void signatur() {
		String signature = getSignature(api_key, "1.0", engCode, projectCode, timestamp, "body");
		log.info(signature);

	}

}
